package com.yunxin.download.server.api;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.Result;
import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.download.server.api.request.DownloadFileRequest;
import com.yunxin.download.server.api.request.DownloadWorldFileRequest;
import com.yunxin.download.server.infra.constant.FileExportConstant;
import com.yunxin.download.server.infra.utils.AliYunOssUtil;
import com.yunxin.download.server.service.extenal.DownloadFileDTO;
import com.yunxin.download.server.service.extenal.FileExportConfigDTO;
import com.yunxin.download.server.infra.constant.enums.DownloadResultCode;
import com.yunxin.download.server.infra.repository.DownloadMethodConfigDao;
import com.yunxin.download.server.infra.support.datasource.DataSourceInitListener;
import com.yunxin.download.server.model.entity.DownloadMethodConfigWithBLOBs;
import com.yunxin.download.server.service.DownloadService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-06-15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/download")
public class DownloadFileController {

    private final DataSourceInitListener dataSourceInitListener;

    private final DownloadMethodConfigDao downloadMethodConfigDao;

    private final DownloadService downloadService;

    @PostMapping("/downloadFile")
    public Result<Boolean> downloadFile(@Validated @RequestBody DownloadFileRequest request) {
        final String dataSourceName = request.getDataSourceName() + request.getSystemCode();
        DataSource dataSource = dataSourceInitListener.getDtaSource(dataSourceName);
        if (Objects.isNull(dataSource)) {
            throw new BusinessException(DownloadResultCode.DATA_SOURCE_ERROR);
        }
        DownloadMethodConfigWithBLOBs methodConfig = downloadMethodConfigDao.selectDownloadMethodConfigByMethodCode(request.getMethodCode(), request.getSystemCode());
        DownloadFileDTO downloadFileDTO = new DownloadFileDTO();
        downloadFileDTO.setDataSourceName(dataSourceName);
        //内容配置项
        List<FileExportConfigDTO> fileExportConfigs = JacksonUtils.X.parse(methodConfig.getExportConfig(), new TypeReference<>() {
        });
        downloadFileDTO.setExportConfig(fileExportConfigs);
        downloadFileDTO.setLimit(500);
        downloadFileDTO.setLimitType(methodConfig.getLimitType());
        downloadFileDTO.setMethodCode(methodConfig.getMethodCode());
        downloadFileDTO.setMethodConfigId(methodConfig.getId());
        downloadFileDTO.setMethodNme(methodConfig.getMethodName());
        downloadFileDTO.setParams(request.getParams());
        downloadFileDTO.setSql(methodConfig.getMethodSql());
        downloadFileDTO.setTemplateUrl(methodConfig.getMethodTemplate());
        downloadFileDTO.setDownloaderName(request.getDownloaderName());
        downloadFileDTO.setIsView(request.getIsView());
        downloadService.downloadFile(downloadFileDTO);
        return Result.success();
    }

    @PostMapping("/downloadWorldFile")
    public Result<Boolean> downloadWorldFile(@Validated @RequestBody DownloadWorldFileRequest request) {
        final String dataSourceName = request.getDataSourceName() + request.getSystemCode();
        DataSource dataSource = dataSourceInitListener.getDtaSource(dataSourceName);
        if (Objects.isNull(dataSource)) {
            throw new BusinessException(DownloadResultCode.DATA_SOURCE_ERROR);
        }
        DownloadMethodConfigWithBLOBs methodConfig = downloadMethodConfigDao.selectDownloadMethodConfigByMethodCode(request.getMethodCode(), request.getSystemCode());
        DownloadFileDTO downloadFileDTO = new DownloadFileDTO();
        downloadFileDTO.setDataSourceName(dataSourceName);
        //内容配置项
        List<FileExportConfigDTO> fileExportConfigs = JacksonUtils.X.parse(methodConfig.getExportConfig(), new TypeReference<>() {
        });
        downloadFileDTO.setExportConfig(fileExportConfigs);
        downloadFileDTO.setLimit(500);
        downloadFileDTO.setLimitType(methodConfig.getLimitType());
        downloadFileDTO.setMethodCode(methodConfig.getMethodCode());
        downloadFileDTO.setMethodConfigId(methodConfig.getId());
        downloadFileDTO.setMethodNme(methodConfig.getMethodName());
        downloadFileDTO.setParams(request.getParams());
        downloadFileDTO.setSql(methodConfig.getMethodSql());
        downloadFileDTO.setTemplateUrl(methodConfig.getMethodTemplate());
        downloadFileDTO.setDownloaderName(request.getDownloaderName());
        downloadFileDTO.setIsView(request.getIsView());
        downloadService.downloadWorldFile(downloadFileDTO);
        return Result.success();
    }


    @GetMapping("/remoteDownloadFile")
    public void remoteDownloadFile(@RequestParam("ossKey")String ossKey) throws IOException {
        String filePath = "C:\\Users\\Administrator\\Desktop\\1111\\" + ossKey;
        InputStream input = AliYunOssUtil.X.download(FileExportConstant.OSS_DOWNLOAD_FILE_TEMPLATE_DIR + ossKey);
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(filePath);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        input.close();
        downloadFile.close();
    }
}
